package com.softmarket.action.manager;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.seasar.framework.log.Logger;
import org.seasar.struts.annotation.Execute;

import com.softmarket.action.BaseAction;
import com.softmarket.dto.DownloadPasswordDto;
import com.softmarket.service.DownloadPasswordService;

public class DownloadPasswordAction extends BaseAction {
	static Logger logger = Logger.getLogger(DownloadPasswordAction.class);

	public String orderNo;

	public String searchDownLoadKey;

	public SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	@Execute(validator = false)
	public String index() {
		return "../downloadPassword.jsp";
	}

	@Execute(validator = false)
	public String doCreatePassword() throws IOException {
		String returnMessage = "";
		if (orderNo == null || orderNo.length() == 0) {
			returnMessage = "注文番号を入力してください。,,";
		} else {
			DownloadPasswordDto dto = new DownloadPasswordDto();
			DownloadPasswordService service = new DownloadPasswordService();
			dto.setId("1");
			dto.setOrderType("1");
			dto.setOrderNo(orderNo);

			List<DownloadPasswordDto> resultList = service.select(dto);

			if (resultList.size() > 0) {
				DownloadPasswordDto last = resultList
						.get(resultList.size() - 1);
				returnMessage = "既存注文," + last.getDownloadKey() + ","
						+ sdf.format(last.getCreateTime());
			} else {
				Date data = new Date();
				dto.setCreateTime(data);
				dto.setDeleteFlg("0");
				String key = service.getDownloadKey();
				;
				dto.setDownloadKey(key);
				if (service.insert(dto)) {
					returnMessage = "作成成功," + key + "," + sdf.format(data);
				} else {
					returnMessage = "作成失敗,,";
				}
			}

		}

		response.getWriter().write(returnMessage);
		return null;
	}

	@Execute(validator = false)
	public String doUpdatePassword() throws IOException {
		String returnMessage = "";
		if (orderNo == null || orderNo.length() == 0) {
			returnMessage = "注文番号を入力してください。,,";
		} else {
			DownloadPasswordDto dto = new DownloadPasswordDto();
			DownloadPasswordService service = new DownloadPasswordService();
			dto.setId("1");
			dto.setOrderType("1");
			dto.setOrderNo(orderNo);

			List<DownloadPasswordDto> resultList = service.select(dto);

			if (resultList.size() == 0) {
				returnMessage = "存在しない注文,,";
			} else {
				Date data = new Date();
				dto.setCreateTime(data);
				dto.setDeleteFlg("0");
				String key = service.getDownloadKey();
				;
				dto.setDownloadKey(key);
				if (service.update(dto)) {
					returnMessage = "再作成成功," + key + "," + sdf.format(data);
				} else {
					returnMessage = "再作成失敗,,";
				}
			}

		}

		response.getWriter().write(returnMessage);
		return null;
	}

}
